package com.emm.yixun.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.DistributionService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.MsgSettingService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Notice;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ReceiverNoticeDto;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.NoticeTypeEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.system.service.NoticeServiceFacade;
import com.emm.yixun.system.service.impl.manage.CustomerCareNoticeManage;
import com.emm.yixun.system.service.impl.manage.CustomerCarePushMsgCurrManage;
import com.emm.yixun.system.service.impl.manage.CustomerCarePushMsgManage;
import com.emm.yixun.system.service.impl.manage.CustomerManageNoticeManage;
import com.emm.yixun.system.service.impl.manage.CustomerManagePushMsgManage;
import com.emm.yixun.system.service.impl.manage.CustomerNoPaymentNoticeManage;
import com.emm.yixun.system.service.impl.manage.CustomerNoPaymentPushMsgCurrManage;
import com.emm.yixun.system.service.impl.manage.CustomerNoSignedNoticeManage;
import com.emm.yixun.system.service.impl.manage.CustomerNoSignedPushMsgCurrManage;
import com.emm.yixun.system.service.impl.manage.SysNoticeManage;
import com.emm.yixun.system.service.impl.manage.UserCareNoticeManage;
import com.emm.yixun.system.service.impl.manage.UserCarePushMsgCurrManage;

@Service("noticeServiceFacade")
@WebService(name = "com.emm.yixun.system.service.NoticeServiceFacade")
public class NoticeServiceFacadeImpl implements NoticeServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private NoticeService service;
	@Autowired
	private MsgSettingService msgSettingService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private SysNoticeManage sysNoticeManage;
	@Autowired
	private DistributionService distributionService;
	@Autowired
	private UserService userService;
	@Autowired
	private CustomerManageNoticeManage customerManageNoticeManage;
	@Autowired
	private CustomerManagePushMsgManage customerManagePushMsgManage;
	@Autowired
	private CustomerCareNoticeManage customerCareNoticeManage;
	@Autowired
	private CustomerCarePushMsgManage customerCarePushMsgManage;
	@Autowired
	private CustomerCarePushMsgCurrManage customerCarePushMsgCurrManage;
	@Autowired
	private UserCareNoticeManage userCareNoticeManage;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private UserCarePushMsgCurrManage userCarePushMsgCurrManage;
	@Autowired
	private CustomerNoSignedNoticeManage customerNoSignedNoticeManage;
	@Autowired
	private CustomerNoSignedPushMsgCurrManage customerNoSignedPushMsgCurrManage;
	@Autowired
	private CustomerNoPaymentNoticeManage customerNoPaymentNoticeManage;
	@Autowired
	private CustomerNoPaymentPushMsgCurrManage customerNoPaymentPushMsgCurrManage;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private DataPermissionService dataPermissionService;

	@Override
	public Response<NoticeDto> save(NoticeDto dto) {
		Response<NoticeDto> response = new Response<NoticeDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			NoticeDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			// 推送消息：公告
			Map<String, String> pushMap = new HashMap<String, String>();
			pushMap.put("action", "公告列表");
			pushMap.put("pushType", NoticeTypeEnum.NOTICE.getNo());
			pushMap.put("projectCode", dto.getProjectCode());
			ProjectDto proDto = new ProjectDto();
			if (StringUtils.isNotEmpty(dto.getProjectCode())) {
				proDto.setProjectCode(dto.getProjectCode());
				Project project = projectService.selectByDto(proDto);
				pushMap.put("projectName", project.getProjectName());
			}
			String context = dto.getContent();
			appPushService.pushMessage2(dto.getMerchantId(), dto.getProjectCode(), context, "公告", pushMap);
			response.success(mDto);
			// 更新消息发送状态
			NoticeDto noticeDto = new NoticeDto();
			noticeDto.setId(mDto.getId());
			noticeDto.setIsSend(IsSendEnum.SEND.getNo());
			noticeService.update(noticeDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(NoticeDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			NoticeDto mDto = new NoticeDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Notice> findById(Long id) {
		Response<Notice> response = new Response<Notice>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Notice entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Notice> findByDto(NoticeDto dto) {
		ResponseList<Notice> response = new ResponseList<Notice>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Notice> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<Notice> findPageByDto(NoticeDto dto, Integer begin, Integer row) {
		Page<Notice> response = new Page<Notice>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(),
						dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				//如果没有任何权限的时候
				String str = dataPermissionArr[1];
				if(StringUtils.isNotEmpty(str)&&str.replace(" ", "").length()>0){
					dto.setDataPermission(dataPermissionArr[1]);
				}else{
					dto.setDataPermission("AND 1=2");
				}
				
			}
			
			Page<Notice> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			page.setPageSize(row);
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public CommonResDTO customerManageNotice() {
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerManageNoticeManage.createNotice();
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("客户维护消息创建失败," + ex.getMessage());
			resDto.setResult("0");
		}
		return resDto;
	}

	@Override
	public Response<CommonResDTO> customerCareNotice() {
		Response<CommonResDTO> response = new Response<CommonResDTO>();
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerCareNoticeManage.createNotice();
			response.success(resDto);
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("客户关怀消息创建失败," + ex.getMessage());
			resDto.setResult("0");
			response.setSuccess(false);
		}
		return response;
	}

	@Override
	public Response<CommonResDTO> userCareNotice() {
		Response<CommonResDTO> response = new Response<CommonResDTO>();
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = userCareNoticeManage.createNotice();
			response.success(resDto);
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("员工关怀消息创建失败," + ex.getMessage());
			resDto.setResult("0");
			response.setSuccess(false);
		}
		return response;
	}

	@Override
	public CommonResDTO customerManagePushMsg() {
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerManagePushMsgManage.pushMsg();
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("推送客户维护消息失败," + ex.getMessage());
			resDto.setResult("0");
		}
		return resDto;
	}

	@Override
	public Response<CommonResDTO> customerCarePushMsg() {
		Response<CommonResDTO> response = new Response<CommonResDTO>();
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerCarePushMsgManage.pushMsg();
			response.success(resDto);
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("推送客户关怀消息,生日纪念日提前通知失败," + ex.getMessage());
			resDto.setResult("0");
			response.setSuccess(false);
		}
		return response;
	}

	@Override
	public Response<CommonResDTO> customerCarePushMsgCurr() {
		Response<CommonResDTO> response = new Response<CommonResDTO>();
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerCarePushMsgCurrManage.pushMsg();
			response.success(resDto);
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("推送客户关怀消息,生日及纪念日当天通知失败," + ex.getMessage());
			resDto.setResult("0");
			response.setSuccess(false);
		}
		return response;
	}

	@Override
	public Response<CommonResDTO> userCarePushMsgCurr() {
		Response<CommonResDTO> response = new Response<CommonResDTO>();
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = userCarePushMsgCurrManage.pushMsg();
			response.success(resDto);
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("推送员工关怀消息,生日及入职周年当天通知失败," + ex.getMessage());
			resDto.setResult("0");
			response.setSuccess(false);
		}
		return response;
	}

	@Override
	public Response<CommonResDTO> customerNoSignedNotice() {
		Response<CommonResDTO> response = new Response<CommonResDTO>();
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerNoSignedNoticeManage.createNotice();
			response.success(resDto);
		} catch (Exception ex) {
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("创建逾期未签约消息失败," + ex.getMessage());
			resDto.setResult("0");
			response.setSuccess(false);
		}
		return response;
	}

	@Override
	public CommonResDTO customerNoSignedPushMsgCurr() {
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerNoSignedPushMsgCurrManage.pushMsg();
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("推送逾期未签约消息,通知失败," + ex.getMessage());
			resDto.setResult("0");
		}
		return resDto;
	}

	@Override
	public Response<CommonResDTO> customerNoPaymentNotice() {
		Response<CommonResDTO> response = new Response<CommonResDTO>();
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerNoPaymentNoticeManage.createNotice();
			response.success(resDto);
		} catch (Exception ex) {
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("创建逾期未付款消息失败," + ex.getMessage());
			resDto.setResult("0");
			response.setSuccess(false);
		}
		return response;
	}

	@Override
	public CommonResDTO customerNoPaymentPushMsgCurr() {
		CommonResDTO resDto = new CommonResDTO();
		try {
			resDto = customerNoPaymentPushMsgCurrManage.pushMsg();
		} catch (Exception ex) {
			ex.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("推送逾期未付款消息,通知失败," + ex.getMessage());
			resDto.setResult("0");
		}
		return resDto;
	}

	@Override
	public Response<Integer> count(NoticeDto dto) {
		Response<Integer> response = new Response<Integer>();
		try {
			int count = service.count(dto);
			response.success(Integer.valueOf(count));
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("统计数据数量错误：{}", e);
		}
		return response;
	}

	/**
	 * 统计某一大类的Notice数量
	 * 
	 * @param dto
	 * @return
	 */
	@Override
	public Response<Integer> noticeCount(NoticeDto dto) {
		Response<Integer> response = new Response<Integer>();
		try {
			int count = service.noticeCount(dto);
			response.success(Integer.valueOf(count));
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("统计数据数量错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<Notice> getNoticeList(NoticeDto dto, Integer begin, Integer row) {
		Page<Notice> response = new Page<Notice>();
		response.setPageSize(row);
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Notice> page = service.getNoticeList(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			page.setPageSize(row);
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	/**
	 * 查询用户消息并分页
	 */
	public Page<ReceiverNoticeDto> receiverNoticePage(ReceiverNoticeDto receiverNoticeDto, Integer begin,
			Integer pageSize) {
		Page<ReceiverNoticeDto> response = new Page<ReceiverNoticeDto>();
		try {
			if (null == receiverNoticeDto || null == begin || null == pageSize) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<ReceiverNoticeDto> page = service.receiverNoticePage(receiverNoticeDto, begin, pageSize);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			page.setPageSize(pageSize);
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	public Response<Integer> receiverNoticeCount(ReceiverNoticeDto receiverNoticeDto) {
		Response<Integer> response = new Response<Integer>();
		try {
			int count = service.receiverNoticeCount(receiverNoticeDto);
			response.success(Integer.valueOf(count));
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("统计数据数量错误：{}", e);
		}
		return response;
	}

}
